package com.mall.fliter;

import com.central.common.utils.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.security.TokenManager;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenVerifyFilter extends OncePerRequestFilter {

    @Autowired
    private TokenManager tokenManager = new TokenManager();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        设置返回中文
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        //查看是否是登录请求
        String uri = request.getRequestURI();

        //如果未登录或者登录请求
        if ("/login".equals(uri)) {
            filterChain.doFilter(request,response);
        }
        //如果已经登录  检查token
        String token = request.getHeader("token");
        //如果没有token直接返回没有凭证
        if (token == null) {
            ResponseUtil.responseFailed(new ObjectMapper(),response,"没有凭证");
            return;
        }
        //有token解析token是否合法
        try {
            String userInfoFromToken = tokenManager.getUserInfoFromToken(token);

        }catch (ExpiredJwtException expiredJwtException) {
            ResponseUtil.responseFailed(new ObjectMapper(),response,"token过期");
            return;
        }catch (MalformedJwtException malformedJwtException) {
            ResponseUtil.responseFailed(new ObjectMapper(), response, "非法伪造token");
            return;
        } catch (JwtException jwtException) {
            ResponseUtil.responseFailed(new ObjectMapper(), response, "非法伪造token");
            return;
        }
        filterChain.doFilter(request,response);
    }

}
